import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import hangman.HangmanGame;;

/**
 * Servlet implementation class Hangman
 */
public class Hangman extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Hangman() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		
		if( session.isNew() ){
			HangmanGame hg = new HangmanGame();
			session.setAttribute("game", hg);
			
		}else{
			
			HangmanGame hg = (HangmanGame)session.getAttribute("game");
			
			if(hg.isOver()){
				HangmanGame hag = new HangmanGame();
				session.setAttribute("game", hag);				
			}
		}
		
		RequestDispatcher rd = request.getRequestDispatcher("hangman.jsp");
		rd.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		
		String s = request.getParameter("text");
		
		System.out.println(s);
		
		HttpSession session = request.getSession();
		
		HangmanGame hg = (HangmanGame)session.getAttribute("game");
		hg.guess(s.charAt(0));
		session.removeAttribute("game");
		session.setAttribute("game", hg);
		
		RequestDispatcher rd = request.getRequestDispatcher("hangman.jsp");
		rd.forward(request, response);		
	}

}
